﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace UniversityCourses.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class SessionExpireFilterAttribute : ActionFilterAttribute
    {
        public string Controller { get; set; }
        public string Action { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;

            string returnUrl = ctx.Request.RawUrl;

            // If the browser session or authentication session has expired...
            if (ctx.Session["UserName"] == null || !filterContext.HttpContext.Request.IsAuthenticated)
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    // redirect on the client to the login page
                    JavaScriptResult js = new JavaScriptResult();
                    js.Script = "location.reload();";
                    filterContext.Result = js;
                }
                else
                {
                    //redirect on the server to the login page
                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary {
                        { "Controller", this.Controller },
                        { "Action", this.Action },
                        { "returnUrl", returnUrl}
                });
                }
            }

            base.OnActionExecuting(filterContext);
        }
    }

}